package org.example;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class LockMain {

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main开始");
        ZkClient zkClient = new ZkClient();
        new Thread(() -> {
            try {
                System.out.println(("第一个线程执行"));
                checkAndLock(zkClient, 5L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        TimeUnit.SECONDS.sleep(1L);
        new Thread(() -> {
            try {
                System.out.println(("第二个线程执行"));
                checkAndLock(zkClient, 3L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        System.out.println(("等待中......"));
    }

    public static void checkAndLock(ZkClient zkClient, Long time) throws InterruptedException {
        ZkDistributedLock lock = zkClient.getLock("lock");
        lock.lock();
        System.out.println(("业务执行开始:" + Thread.currentThread().getName()) + " :" + System.currentTimeMillis());
        TimeUnit.SECONDS.sleep(time);
        System.out.println(("业务执行结束:")  + Thread.currentThread().getName() + " :" + System.currentTimeMillis());
        lock.unlock();
    }
}
